public class Solution {
    /*
     * 二叉树的锯齿形层序遍历
     * BFS
     * */
    public static void reserve(List<Integer> list) {
        int size = list.size();
        int[] array = new int[size];
        for (int i = size - 1; i >= 0; i--) {
            array[i] = list.remove(0);
        }
        for (int x : array) {
            list.add(x);
        }
    }

    public static List<List<Integer>> zigzagLevelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        //给个标记，从左入队 还是从右入队
        boolean flag = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            List<Integer> alist = new ArrayList<>();
            while (size > 0) {
                TreeNode node = queue.poll();
                alist.add(node.val);
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            if (!flag) {
                reserve(alist);
            }
            flag = !flag;
            list.add(alist);
        }
        return list;
    }

    /*
     * 双端队列实现 deque
     * 我里giao
     *
     * */
    public static List<List<Integer>> zigzagLevelOrder2(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if (root == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        //给个标记，从左入队 还是从右入队
        boolean flag = true;
        while (!queue.isEmpty()) {
            int size = queue.size();
            Deque<Integer> deque = new LinkedList<>();
//            List<Integer> alist = new ArrayList<>(size);
            while (size > 0) {
                TreeNode node = queue.poll();
                if (flag) {
                    deque.addLast(node.val);
                } else {
                    deque.addFirst(node.val);
                }
//                if(flag) {
//                    alist.add(node.val);
//                }else {
//                必须index<size才能实现，操了
//                    alist.add(size - 1, node.val);
//                }
                if (node.left != null) {
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    queue.offer(node.right);
                }
                size--;
            }
            flag = !flag;
            list.add(new ArrayList<>(deque));
        }
        return list;
    }
}